<?php

namespace App\Http\Controllers;

use App\Models\DoctorModel;
use App\Models\DoctorPatientModel;
use App\Models\PatientModel;
use EasyWeChat\Kernel\Support\File;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class ChatController extends Controller
{

    protected $chatRecordTable = 'chatroom:chat-records';
    protected $jsApiList = ['chooseImage', 'uploadImage'];
    public function __construct()
    {
        $this->app = \EasyWeChat\Factory::officialAccount(config('wechat.official_account.default'));
        // 创建缓存实例
        $cache = new RedisAdapter(app('redis')->connection()->client());
        // 替换应用中的缓存
        $this->app->rebind('cache', $cache);
    }

    /**
     * 聊天列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function chatList(Request $request)
    {
        $doctorId = $request->get('doctorid');
        $keyword = $request->get('keyword', '');
        $relations = DoctorPatientModel::whereHas('patient', function (Builder $query) use ($keyword) {
            if ($keyword != '') {
                $query->where('patients_name', 'like', "%$keyword%");
            }
        })
        ->where('doctor_id', $doctorId)
        ->get();
        // 重新组装数据
        $data = [];
        foreach ($relations as $relation) {
            if (is_null($relation->chatroom_id)) continue;
            if (!isset($relation->patient) || is_null($relation->patient)) continue;

            // 查询聊天记录
            $chatRecords = Redis::hget($this->chatRecordTable, 'chatroom:'.$relation->chatroom_id);
            $chatRecords = json_decode($chatRecords, true);
            $chatContent = '';
            $chatTime = '';
            if (!is_null($chatRecords)) {
                $chatRecords = array_reverse($chatRecords);
                $chatContent = !empty($chatRecords) ? $chatRecords[0]['content'] : '';
                $chatTime = !empty($chatRecords) ? $chatRecords[0]['time'] : '';
                if (Carbon::parse($chatTime)->isToday()) {
                    $chatTime = Carbon::parse($chatTime)->format('H:i:s');
                } else {
                    $chatTime = Carbon::parse($chatTime)->format('Y-m-d');
                }
            }

            $data[] = [
                'patient_name' => $relation->patient->patients_name,
                'patient_img' => $relation->patient->patients_img ?: "https://api.multiavatar.com/".$relation->patient->data_id.".png",
                'chatroom_id' => $relation->chatroom_id,
                'chat_content' => $chatContent,
                'chat_time' => $chatTime,
            ];
        }
        return view('chatroom/list', ['list' => $data, 'doctorId' => $doctorId, 'keyword' => $keyword]);
    }

    /**
     * 聊天页
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function chatroom(Request $request)
    {

        $config = $this->app->jssdk->buildConfig($this->jsApiList, false);
        $chatRecords = Redis::hget($this->chatRecordTable, 'chatroom:'.$request->get('roomid'));
        $chatRecords = json_decode($chatRecords, true);

        return view('chatroom/detail', ['config' => $config, 'chatRecords' => $chatRecords, 'userId' => $request->get('userid')]);
    }

    /**
     * 下载微信资源
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function downloadWxRes(Request $request)
    {
        // $mediaId = 'VsFUyq8E5fHO-AnG4FIL0j3SSQw2RNxrctuEU5S8G3-8ngwBkRoLcx4rzMo-M9iz';
        $mediaId = $request->get('media_id');
        $stream = $this->app->media->get($mediaId);

        $contents = $stream->getBody()->getContents();
        if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {

            // 以内容 md5 为文件名存到本地
            // $stream->save('../storage/app/chatroom');

            // 上传到阿里云
            $client = new Client();
            $res = $client->request('POST', $request->getHost() . '/jeecg-boot/sys/common/upload', [
                'multipart' => [
                    [
                        'name'     => 'file',
                        'contents' => $contents,
                        'filename' => $mediaId . File::getStreamExt($contents)
                    ]
                ]
            ]);

            $body = $res->getBody(); //获得接口返回的主体对象
            return $body->getContents(); //获得主体内容
        }
        return response()->header('Content-Type', 'application/json')->json([
            'success' => false,
            'message' => '未知文件类型',
        ]);
    }
}
